<template>
  <div class="matrix-container">
    <canvas ref="matrixCanvas"></canvas>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

// Canvas and context
const matrixCanvas = ref(null);
let ctx = null;

// Variables
/*const katakana = 'アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヰヱヲン';
const latin = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const nums = '0123456789'*/;
const bamum = 'ꚠꚡꚢꚣꚤꚥꚦꚧꚨꚩꚪꚫꚬꚭꚮꚯꚰꚱꚲꚳꚴꚵꚶꚷꚸꚹꚺꚻꚼꚽꚾꚿꛀꛁꛂꛃꛄꛅꛆꛇꛈꛉꛊꛋꛌꛍꛎꛏꛐꛑꛒꛓꛔꛕꛖꛗꛘꛙꛚꛛꛜꛝꛞꛟꛠꛡꛢꛣꛤꛥꛦꛧꛨꛩꛪꛫꛬꛭꛮꛯ';

const alphabet = ref(bamum); // 默认字符集
const fontSize = ref(16); // 默认字体大小
const columns = ref(0);
const rainDrops = ref([]);
const color = ref('#0f0'); // 默认颜色
const speed = ref(50); // 默认速度
const fadeSpeed = ref(0.05); // 默认渐隐速度
const horizontalMovement = ref(3); // 默认水平移动速度
const cycleColorActive = ref(true); // 默认开启颜色循环
const hue = ref(0);

// Interval management
let interval = null;

// Methods
const draw = () => {
  ctx.fillStyle = `rgba(0, 0, 0, ${fadeSpeed.value})`;
  ctx.fillRect(0, 0, matrixCanvas.value.width, matrixCanvas.value.height);

  if (cycleColorActive.value) {
    hue.value = (hue.value + 1) % 360;
    color.value = `hsl(${hue.value}, 100%, 50%)`;
  }

  ctx.fillStyle = color.value;
  ctx.font = `${fontSize.value}px Noto Sans Bamum`;

  for (let i = 0; i < rainDrops.value.length; i++) {
    const text = alphabet.value.charAt(Math.floor(Math.random() * alphabet.value.length));
    ctx.fillText(text, i * fontSize.value + rainDrops.value[i] * horizontalMovement.value, rainDrops.value[i] * fontSize.value);

    if (rainDrops.value[i] * fontSize.value > matrixCanvas.value.height && Math.random() > 0.975) {
      rainDrops.value[i] = 0;
    }
    rainDrops.value[i]++;
  }
};

// Lifecycle hooks
onMounted(() => {
  ctx = matrixCanvas.value.getContext('2d');
  matrixCanvas.value.height = window.innerHeight;
  matrixCanvas.value.width = window.innerWidth;
  columns.value = matrixCanvas.value.width / fontSize.value;
  rainDrops.value = Array(Math.ceil(columns.value)).fill(1);

  interval = setInterval(draw, speed.value);

  window.addEventListener('resize', () => {
    matrixCanvas.value.height = window.innerHeight;
    matrixCanvas.value.width = window.innerWidth;
    columns.value = matrixCanvas.value.width / fontSize.value;
    rainDrops.value = Array(Math.ceil(columns.value)).fill(1);
  });
});

onUnmounted(() => {
  clearInterval(interval);
});
</script>

<style scoped>
.matrix-container {
  position: relative;
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background-color: #000;
}

canvas {
  display: block;
}
</style>
